package com.oak.broke.exception.handler;

import com.oak.broke.constant.ResponseConstant;
import com.oak.broke.model.vip.base.ResponseMessage;
import com.oak.broke.utils.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author tanghan
 * @Description 参数校验异常处理
 * @date 2023/04/13/ 14:05:00
 */
@Slf4j
@RestControllerAdvice
@Order(0)
public class ParamValidExceptionHandler {

    /**
     * 参数校验不通过异常处理
     *
     * @param e 校验异常
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseMessage handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        StringBuilder errMsg = new StringBuilder();
        for (FieldError fieldError : result.getFieldErrors()) {
            errMsg.append(fieldError.getDefaultMessage()).append(",");
        }
        // 删除最后一个,
        log.error("请求参数校验失败，原因:{}", errMsg);
        errMsg.deleteCharAt(errMsg.length() - 1);
        // 规整提示 信息
        String msg = MessageUtil.getMessage(ResponseConstant.PARAM_VALID_EXCEPTION, errMsg.toString());
        return ResponseMessage.fail(ResponseConstant.PARAM_VALID_EXCEPTION, msg);
    }
}
